package Concurrency2.Chapter05_Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Instruction：
 * 验证park阻塞的线程是否释放锁
 * 锁定的临界区, 是否可以被另一个线程进入
 * Author：@author MaLi
 */
public class T01_LockSupport {
    private static final Lock lock = new ReentrantLock();

    private static void method(boolean flag) {
        if (flag) {
            lock.lock();
            try {
                System.out.println("线程1进入临界区, 持有锁中, 准备park...");
                LockSupport.park();
            } finally {
                lock.unlock();
            }
        } else {
            System.err.println("线程2开始执行, 准备获取锁...");
            lock.lock();
            try {
                System.out.println("线程2获取锁, 进入临界区");
            } finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // 线程1, 加锁进入临界区, park阻塞住
        Thread t1 = new Thread(() -> method(true), "线程1");
        // 线程2, 是否可以进入临界区
        Thread t2 = new Thread(() -> method(false), "线程2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("main thread is running...");
    }
}
